<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('unit', 'tasks');
pc_base::load_app_class('utility','tasks',0);

class tasks extends admin {
	function __construct() {
		parent::__construct();
		$this->db = pc_base::load_model('module_model');
		$this->tasks_db = pc_base::load_model('tasks_model');
		$this->tasks_log_db = pc_base::load_model('tasks_log_model');
	}
	public function init() {
		$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
		$show_header = true;
		$show_validator = true;
		$where='';	
		$tasks = $this->tasks_db->listinfo($where, 'taskid DESC', $page, 20);
		$pages = $this->tasks_db->pages;
		include $this->admin_tpl('tasks_manage');			
	}
	
	public function add() {
		if(isset($_POST['dosubmit'])){
			$info  =  $_POST['info'];
			if($info['taskname'] == '') showmessage('任务名称不能为空', HTTP_REFERER);
			if($info['tasktime'] == '') showmessage('任务时间不能为空', HTTP_REFERER);
			$info = $_POST['info'];
			$info['taskon'] = 0;
			$info['taskswitch'] = 0;
			$info['taskflag'] = time ();
			$info['addtime'] = time();			
			$this->tasks_db->insert($info);
			if($this->tasks_db->insert_id()){
				showmessage('添加成功','?m=tasks&c=tasks&a=init');
			}
		}else {
			$show_header = true;
			$show_validator = true;
			include $this->admin_tpl('tasks_add');		
		}	
	}
	public function edit() {
		if(isset($_POST['dosubmit'])){
			$info  =  $_POST['info'];
			if($info['taskname'] == '') showmessage('任务名称不能为空', HTTP_REFERER);
			if($info['tasktime'] == '') showmessage('任务时间不能为空', HTTP_REFERER);
			$info = $_POST['info'];		
			$this->tasks_db->update($info,array('taskid'=>$_POST['taskid']));
			showmessage('修改成功','?m=tasks&c=tasks&a=init');
		}else {
			$show_header = true;
			$show_validator = true;
			$taskid  =  $_GET['taskid'];
			$taskinfo = $this->tasks_db->get_one(array('taskid'=> $taskid));
			include $this->admin_tpl('tasks_edit');		
		}	
	}
	public function start() {
		$taskid = $_GET['taskid'];
		if (!preg_match ( '/^[0-9.-]+$/', $taskid )){
			showmessage ( '参数无效！请勿提交非法url', HTTP_REFERER);
		}
		$result = $this->tasks_db->get_one(array('taskid'=>$taskid));
		if(!$result) showmessage( '任务不存在', HTTP_REFERER);
		//检测任务状态是否已经开始，0为未开始，1为已经开始 
		if ($result["taskon"] == 1) {
			showmessage("任务还在进行中，请等待任务结束", "?m=tasks&c=tasks&a=init" );
		} else {
			$newtime = time();
			//标记当前任务已经开始，做状态保护
			$this->tasks_db->update(array('taskswitch'=>1,'taskon'=>1,'addtime'=>$newtime),array('taskid'=>$taskid));
			//记录开始任务的时间并写入日志
			$logtaskid = $taskid;
			$ltime = time ();
			$rs = $this->tasks_db->get_one(array('taskid'=>$taskid),'tasktype');
			
			$tasktype = $rs['tasktype'];
			$this->tasks_log_db->insert(array('logtaskid'=>$logtaskid,'loginfo'=>'启动','logtime'=>$ltime,'logsize'=>'NONE'));
			include $this->admin_tpl('task_start');
		}
	}
	
	public function stop() {
		$taskid = $_GET['taskid'];
		if (!preg_match ( '/^[0-9.-]+$/', $taskid )){
			showmessage ( '参数无效！请勿提交非法url', HTTP_REFERER);
		}
		$this->tasks_db->update(array('taskswitch'=>0),array('taskid'=>$taskid));
		$this->tasks_log_db->insert(array('logtaskid'=>$taskid,'loginfo'=>'等待','logtime'=>time(),'logsize'=>'NONE'));

		showmessage ( '任务将在下一次执行时结束', "?m=tasks&c=tasks&a=init");
	}
	public function log() {
		$logtaskid = $_GET['taskid'];
		if (!preg_match ( '/^[0-9.-]+$/', $logtaskid )){
			showmessage ( '参数无效！请勿提交非法url', HTTP_REFERER);
		}
		$page = $_GET['page'] ? $_GET['page'] : '1';
		$tasks = $this->tasks_log_db->listinfo(array('logtaskid'=>$logtaskid),$order = 'logid desc',$page, $pagesize = '20');
		$pages = $this->tasks_log_db->pages;
		
		
		$runtimes = $this->countlog ("logtaskid=".$logtaskid." AND loginfo != '启动' AND loginfo != '等待'");
		$runok = $this->countlog ("logtaskid=" . $logtaskid . " AND loginfo = '成功'");
		$runerr = $this->countlog ("logtaskid=" . $logtaskid . " AND loginfo = '结束'");
		
		$logs = $this->findlog ("logtaskid=" . $logtaskid . " AND loginfo = '启动' ORDER BY logtime ASC");		
		if (is_array($logs)) $begtime = $logs['logtime'];
		$logs = $this->findlog ("logtaskid=".$logtaskid." AND loginfo = '成功' ORDER BY logtime DESC" );
		if (is_array($logs)) $endtime = $logs['logtime'];
		
				
		$logs = $this->listedit ($logtaskid);
		if (is_array($logs)){
				$taskname = $logs['taskname'];
				$tasktime = $logs['tasktime'];
				$runtime = $logs['runtime'];
				$taskswitch = $logs['taskswitch'];
		}
		$counttime = 0;
		$alltime = $endtime - $begtime;
		if ($taskswitch > 0) {
			$maxtime = 5; //设置报警阀值
			$maxtime = $maxtime * $runok;
			$counttime = time () - ($endtime + $tasktime * 60 + $maxtime);
			$countmin = ceil ( $counttime / 60 );
		}		
		$show_dialog = true;
		include $this->admin_tpl('tasks_log');
	}
	
	public function logdel() {
		$logtaskid = $_GET['logtaskid'];
		$deltype = $_GET['deltype'];
		if (!preg_match ( '/^[0-9.-]+$/', $logtaskid)){
			showmessage ( '参数无效！请勿提交非法url', HTTP_REFERER);
		}
		$this->tasks_log_db->delete("logtaskid=$logtaskid AND logtime<$deltype" );
		showmessage ( '删除成功', "?m=tasks&c=tasks&a=init" );
	}
	
	public function listedit($taskid) {
		$array = array ();
		$result = $this->tasks_db->get_one(array('taskid'=>$taskid));
		return $result;
	}
	
	public function countlog($where = "") {
		$number = $this->tasks_log_db->count($where);
		return $number;
	}
	
	public function findlog($where = "") {
		$array = array ();
		$result = $this->tasks_log_db->get_one($where);
		return $result;
	}
	/**
	 * 删除
	 */
	public function delete() {
		$taskidarr = isset($_POST['taskid']) ? $_POST['taskid'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
		$where = to_sqls($taskidarr, '', 'taskid');		
		if ($this->tasks_db->delete($where)) {
			showmessage(L('operation_success'), HTTP_REFERER);
		} else {
			showmessage(L('operation_failure'), HTTP_REFERER);
		}
	}
		public function index() {
		$taskid = $_GET['taskid'];
		ignore_user_abort(); //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
		set_time_limit ( 0 ); // 执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
		do {
			$res=$this->tasks_db->get_one(array('taskid'=>$taskid));
			// 得到下次运行时间
			$interval = $res['tasktime'] * 60;			
			//检测本次任务开关，0为关闭，1为继续，如果退出，写入日志
			if ($res["taskswitch"] == 0) {
				$ltime = time ();
				$this->tasks_db->update(array('taskon'=>0),array('taskid'=>$taskid));
				$this->tasks_log_db->insert(array('logtaskid'=>$taskid,'loginfo'=>'结束','logtime'=>time(),'logsize'=>'NONE'));
				exit ();
			}
			//检测最终任务状态，执行最关键一步
			if ($res) {
				$html = pc_base::load_app_class('html','content'); //加载pc 生成页面的类
				$filesize = $html->index(); //生成页面并得到页面大小
				$lsize = sizecount ($filesize); //格式化文件大小
				$ltime = time (); //记录任务完毕的时间并写入日志
				$this->tasks_log_db->insert(array('logtaskid'=>$taskid,'loginfo'=>'成功','logtime'=>$ltime,'logsize'=>$lsize));
				sleep( $interval ); // 等待一个周期
			} else {
				exit (); //找不到任务时停止（适用于删除了已经开始的任务）
			}
		} while ( true ); //无限循环
	}
}
?>